package com.house.rent;

import android.content.Context;
import android.text.TextUtils;

import androidx.multidex.MultiDex;
import androidx.multidex.MultiDexApplication;

import com.base.lib.util.ScreenManager;
import com.house.rent.entity.UserEntity;
import com.house.rent.manager.ImageManager;
import com.house.rent.util.PreferencesUtils;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheEntity;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.model.HttpHeaders;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;

public class App extends MultiDexApplication {

    private static App instance;

    private UserEntity mUserEntity;

    public static App getInstance() {
        return instance;
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;

        initNetwork();
        ImageManager.getInstance().init(this);
        ScreenManager.getInstance().init(this);
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        ImageManager.getInstance().clearMemoryCaches();
    }

    public UserEntity getUserEntity() {
        if (mUserEntity == null) {
            mUserEntity = PreferencesUtils.getUserEntity();
        }
        return mUserEntity;
    }

    public void saveUserEntity(UserEntity userEntity) {
        if (userEntity != null) {
            this.mUserEntity = userEntity;
            PreferencesUtils.putUserEntity(userEntity);
        }
    }

    /**
     * 初始化网络请求
     */
    public void initNetwork() {
        //设置请求头
        HttpHeaders headers = new HttpHeaders("Content-Type", "application/json;charset=utf-8");
        try {
            OkHttpClient.Builder builder = new OkHttpClient.Builder();
            builder.connectTimeout(15, TimeUnit.SECONDS)
                    .readTimeout(15, TimeUnit.SECONDS)
                    .writeTimeout(15, TimeUnit.SECONDS);
            OkGo.getInstance().init(this)
                    .setOkHttpClient(builder.build())
                    .setCacheMode(CacheMode.NO_CACHE)
                    .setCacheTime(CacheEntity.CACHE_NEVER_EXPIRE)
                    .setRetryCount(3)
                    .addCommonHeaders(headers);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public boolean isLogin() {
        return !TextUtils.isEmpty(getUserEntity().getMobile());
    }

    public void logout() {
        UserEntity userEntity = new UserEntity();
        userEntity.setMobile(getUserEntity().getMobile());
        PreferencesUtils.putUserEntity(userEntity);

        mUserEntity = null;
    }
}
